(function($){
var hash = '';
var	day_btc = false;
var tx_btc = false;
var day_ltc = false;
var tx_ltc = false;
var qukuai = l("blockinfo_url");
var dialog_paycheck = null;
var dialog_checkinfo = null;
var dialog_gif = null;
var dialog_payendok = null;
var dialog_payenderror = null;
var tx_info = '';

var dialog_gif= null
var check_type = ''
var check_code = ''
var im =false;
function sendError(message,id){
	$('#'+id).html(message);
}

function isfloat(oNum){
	if(!oNum) return false;
		var strP=/^(\d+(\.\d*)?|\.\d+)(\d+)?$/;
	if(!strP.test(oNum)) return false;
	try{
		if(parseFloat(oNum)!=oNum) return false;
	}catch(ex){
		return false;
	}
	return true;
}

function set_addr(addr){
	if(window.localStorage){
		var addrs = localStorage.addrs;

		if(typeof(addrs) == "undefined"){
			localStorage.addrs = '{"0":"'+addr+'"}';
			//console.log(111);
		}else{
			var none = true;
			 addrs = $.parseJSON(addrs);
			 //console.log(addrs.count);
			 var count = 0;
			for(var i in addrs ){
				if(addr == addrs[i]){
					none = false;
				}
				count++;
			}
			if(none){
				var jsonstr = '{';
				jsonstr = jsonstr + '"0":"'+addr+'"';
				for(var i = 0; i  < count ;i++ ){
				 jsonstr = jsonstr + ',"'+(i+1)+'":"'+addrs[i]+'"';
				}
				jsonstr = jsonstr + "}";
				localStorage.addrs = jsonstr;
			}
		}
	}
}



function scriptListPubkey(redeemScript){
		var r = {};
		for(var i=1;i<redeemScript.chunks.length-2;i++){
			r[i] = redeemScript.chunks[i];
		}
		return r;
	}

function scriptListSigs(scriptSig){
	var r = {};
	if (scriptSig.chunks[0]==0 && scriptSig.chunks[scriptSig.chunks.length-1][scriptSig.chunks[scriptSig.chunks.length-1].length-1]==174){
		for(var i=1;i<scriptSig.chunks.length-1;i++){
			r[i] = scriptSig.chunks[i];
		}
	}
	return r;
}
function countObject(obj){
	var count = 0;
	var i;
	for (i in obj) {
		if (obj.hasOwnProperty(i)) {
			count++;
		}
	}
	return count;
}

function sleep(n) {
		var start = new Date().getTime();
		while (true) if (new Date().getTime() - start > n) break;
}
function clear_input(){
	$(".pay_google").val("");
	$(".dialog_check_width").val("");
	$(".passwd").val("");
}

function payRequest(uuid, ct, tx_hex,check_type,check_code,im)
{
	var _xsrf = getCookie("_xsrf");
	var remark = htmlEncode($("#remark").val());
	if(check_type != ''){
		var code_info = {type:check_type,code:check_code}
	}else{
		var code_info ={type:null}
	}
	//console.log(111)
	$.ajax({
		type: "post", async: false, cache: false, dataType: "text",
		url: "/send",
		data: $.extend({op:'send' ,_xsrf:_xsrf, ct:ct, tx_hex:tx_hex, remark:remark, uuid:uuid, im:im},code_info),
		success: function (result) {
			var json = $.parseJSON(result);
			dialog_gif.close()
			if(json.result == 'ok'){
				var tx_url = '';
				if(ct == 'ltc'){
					tx_url = 'ltc/'
				}

				$("#tx_a").html(json.txid);
				$("#tx_a").attr('href',qukuai+tx_url+'tx/'+json.txid);

				dialog_payendok = new BootstrapDialog({
					type: 'type-default',
					title: l('PaySuccess'),
						message: $('#payendok'),
						closable: true,
						closeByBackdrop: false,
						closeByKeyboard: false,
						autodestroy:false,
						onhide: function(dialogRef){
							location.reload(true);
							clear_input()
       }
				});
				$('#payendok').show()
				dialog_payendok.open();

			}else{
				dialog_payenderror = new BootstrapDialog({
					type: 'type-default',
					title: l('PayFail'),
						message: $('#payenderror'),
						closable: true,
						closeByBackdrop: false,
						closeByKeyboard: false,
						autodestroy:false,
						onhide: function(dialogRef){
							location.reload(true);
							clear_input()
       }
				});
				$('#payenderror').show()
				dialog_payenderror.open();
			}

		},
		error: function () {
		}
	});
}

function calc_fee(vin_len, tx_size)
{
	var expect_size = tx_size * 2;
	return parseInt(expect_size / 1000);
}
$(document).ready( function() {
	$("#cancel").click(function(){
		dialog_checkinfo.close()
	})
	$("#error_btn").click(function(){
		dialog_payenderror.close();
		location.reload(true);
		form.resetForm();
	})
	$("#ok_btn").click(function(){
		dialog_payendok.close();
		location.reload(true);
		form.resetForm();
	})
	$("#send").click(function (){
		$('.help-block').html('');
		$("#sign").button('reset');
		$("#passwd").val('')
		var data = getData();
		userData = $.parseJSON(data);
		ct = $(".coin-type .active").attr("data-coin");
		var sum = 0;
		var u_cf = 0;
		var cf = 0;
		var myaddr = $("#myaddr").val();
		if(userData != null)
		{
			$.each(userData.addrs, function(i, item){
					if(myaddr == ""){
						var tx = item.tx[ct]["cf"];
						sum = sum + getCoinSum(tx);
						sum =sum + getCoinSum(item.tx[ct]["u_cf"]);
						u_cf = u_cf + getCoinSum(item.tx[ct]["u_cf"]);
					}else{
						if(item.addr == myaddr){
							var tx = item.tx[ct]["cf"];
							sum = sum + getCoinSum(tx);
							sum =sum + getCoinSum(item.tx[ct]["u_cf"]);
							u_cf = u_cf + getCoinSum(item.tx[ct]["u_cf"]);
						}
					}
				})
		}
		var txDest = $.trim($('#address').val());
		if(trim(txDest) == ''){
			sendError(l('ReceiveAddressNullError'),'receive_error');
			return ;
		}
		try {
            var addr = new Bitcoin.Address(txDest);
            if(!validate_address(addr, ct))
            {
            	sendError(l('AddressInvalidError'),'receive_error');
				return ;
            }
        } catch(err) {
            sendError(l('AddressInvalidError'),'receive_error');
			return ;
        }

		total_amount = $('#amount').val();
		if(trim(total_amount) == '' || total_amount == 0){
			sendError(l('AmountNullError'),'amount_error');
			return ;
		}
		if(!isfloat(total_amount)){
			sendError(l('AmountInvalidError'),'amount_error');
			return ;
		}
		var cong = parseInt(total_amount*100000000);

		//$('#myModal').modal('show');

		if(userData.free_fee !=null && userData.free_fee[ct]){
			free = l('Free')
			if(cong > sum){
				sendError(l('AmountNotEnoughPay'),'amount_error');
				return ;
			}
		}
		else if(cong >= sum){
			sendError(l('AmountNotEnoughPay'),'amount_error');
			return ;
		}



		if($('#immediate').prop("checked")){
			cf = sum - u_cf;
			if(u_cf > 0){
				if(cong > cf ){
					$("#type_error").html(l("ImConfirmTip_UnconfTx"))
					return false;
				}else{
					$("#type_tis").html(l("ReceiveAddressCond")+" <span class='orange'>"+ l("QuickwalletUserAddress")+"</span> "+ l("Or")+" <span class='orange'>"+ l("HuobiDepositAddress")+"</span>, "+l("ImConfirmEffective") )
				}
			}else{
				$("#type_tis").html(l("ReceiveAddressCond")+" <span class='orange'>"+ l("QuickwalletUserAddress")+"</span> "+ l("Or")+" <span class='orange'>"+ l("HuobiDepositAddress")+"</span>, "+l("ImConfirmEffective") )
			}
		}else{
			$("#type_error").html("")
			$("#type_tis").html("")
		}



		if(ct == 'btc'){
			coin_zh = l('Btc');
			coin_en = "BTC"
			cny_num = (userData.ticker.btc*total_amount).toFixed(2);
			if(cong < 1000){
				$('#amount_error').html(l('BtcAmountTooSmall'));
				$('#immediate').prop("checked",false)
				return ;
			}
			if(userData.validate_phone || userData.validate_ga){
				day_btc = (userData.spent.btc + cong) > userData.btc_day_limit
				tx_btc = cong > userData.btc_tx_limit;
			}
		}else if(ct == 'ltc'){
			coin_zh = l('Ltc');
			coin_en = "LTC"
			cny_num = (userData.ticker.ltc*total_amount).toFixed(2);
			if(cong < 100000){
				$('#amount_error').html(l('LtcAmountTooSmall'));
				$('#immediate').prop("checked",false)
				return ;
			}
			if(userData.validate_phone || userData.validate_ga){
				day_ltc = (userData.spent.ltc + cong) > userData.ltc_day_limit
				tx_ltc = cong > userData.ltc_tx_limit;
			}
		}

		var code_type = '';
		if(userData.validate_phone || userData.validate_ga){
			if(day_btc || tx_btc || day_ltc || tx_ltc){
				$("#check_box").html($("#check_input").html())
				$(".pay_google").click(function (){
				var str = '<div class="col-sm-12"><label for="code">'+l('SmsVCode')+'</label></div><div class="col-sm-7"><input type="text" class="form-control dialog-code phone_code " id="phone_dialog" placeholder="'+l('SmsVCodeInput_Tip')+'"></div><div class="col-sm-2" id="pay_google_re"><a href="javascript:;" class="blue-a lh" onclick="send_sms(2,\'\');get_code(60,\'pay_google\');" >'+l('SendAgain')+'</a></div><div class="col-sm-12 second" id="pay_google_box"><span id="pay_google_time">59</span>'+l('WaitSecondsSendSms')+'</div><div class="col-sm-12 "><p class="help-block red" id="phone_error"></p></div>';
				$("#check_box #pay_google").html(str);
				send_sms(2,"")
				//console.log(111)
				get_code(60,'pay_google');

			});
			$('.check_type button').click(function (){
				$(this).parent().find('button').removeClass('select');
				$(this).addClass('select');
				$("#check_box .check").removeClass("show hidden");
				var sid = $(this).attr('id')+"_son"

				$("#check_box #"+sid).addClass("show");
			})
				if(!userData.validate_phone){
					$('#check_box #phone').remove()
					$('#check_box #phone_son').remove()
					$('#check_box #google').addClass('select');
					$("#check_box #google_son").removeClass("hidden");
					$("#check_box #google_son").addClass("show");
				}
				if(!userData.validate_ga){
					$('#check_box #google').remove()
					$('#check_box #google_son').remove()
				}
			}
		}




			set_addr(txDest);

			 dialog_paycheck = new BootstrapDialog({
				type: 'type-default',
				title: l('PayVerify'),
					message: $('#paycheck'),
					closable: true,
					closeByBackdrop: false,
					closeByKeyboard: false,
					autodestroy:false,
					onhide: function(dialogRef){
					clear_input()
       }
			});
			$('#paycheck').show()
			dialog_paycheck.open();






		/*
		$('#sendconfirm').modal({
			opacity:50,
			minHeight:height,
			minWidth:600,
			closeHTML: '<a title="关闭">&times;</a>'
		});
		*/


	});
	$("#sign").click(function (){
		$('.help-block').html('');
		$("#sign").button('loading');

		var coin_zh ='';
		var txDest = $.trim($('#address').val());
		total_amount = $('#amount').val();
		cong = parseInt(total_amount*100000000);
		if(ct == 'btc'){
			coin_zh = l('Btc');
			coin_en = "BTC"
			cny_num = (userData.ticker.btc*total_amount).toFixed(2);

			if(userData.validate_phone || userData.validate_ga){
				day_btc = (userData.spent.btc + cong) > userData.btc_day_limit
				tx_btc = cong > userData.btc_tx_limit;
			}
		}else if(ct == 'ltc'){
			coin_zh = l('Ltc');
			coin_en = "LTC"
			cny_num = (userData.ticker.ltc*total_amount).toFixed(2);

			if(userData.validate_phone || userData.validate_ga){
				day_ltc = (userData.spent.ltc + cong) > userData.ltc_day_limit
				tx_ltc = cong > userData.ltc_tx_limit;
			}
		}

		if(day_btc || tx_btc || day_ltc || tx_ltc){
			var _xsrf = getCookie("_xsrf");
			var sp = null;
			check_type = $("#check_box  button.select").attr('id');
			if(check_type == 'phone'){
				check_code = $("#check_box #phone_dialog").val()
				if(check_code == ''){
					sendError(l('FormV_SmsVCodeInput'),'check_box #phone_error');
					$("#sign").button('reset');
					return false;
					}
				$.ajax({
				type: "post", async: false, cache: false,
				url: "/ajax/validate",
				data : {type:'phone',code:check_code,sms_type:2,_xsrf:_xsrf},
				dataType: 'json',
				success: function(data){
					sp = data.result					
					}
				});
				if(!sp){
					sendError(l('VerifyPhone_Fail'),'check_box #phone_error');
					$("#sign").button('reset');
					return false;
				}
			}else if(check_type == 'google'){
				check_code = $("#check_box #google_dialog").val()
				if(check_code == ''){
					sendError(l('FormV_GaVCodeInput'),'check_box #google_error');
					$("#sign").button('reset');
					return false;
				}
				$.ajax({
				type: "post", async: false, cache: false,
				url: "/ajax/validate",
				data : {type:'google',code:check_code,_xsrf:_xsrf},
						dataType: 'json',
						success: function(data){
							sp = data.result	
						}
				});
				if(!sp){
					sendError(l('VefiryGa_Fail'),'check_box #google_error');
					$("#sign").button('reset');
					return false;
				}
				
			}
		}


		var passwd = $("#passwd").val();
		var sendTx = new Bitcoin.Transaction();
		var sum = 0;
		var secret = bitDecrypt(userData.payload, passwd);
		if(secret == 'error'){
			sendError(l('PayPwd_ErrWrong'),'sign_error');
			$("#sign").button('reset');
			return ;
		}
		tx_info = make_tx();
		if(tx_info == ""){
			dialog_payenderror = new BootstrapDialog({
					type: 'type-default',
					title: l('PayFail'),
					message: $('#payenderror'),
					closable: true,
					closeByBackdrop: false,
					closeByKeyboard: false,
					autodestroy:false,
					onhide: function(dialogRef){
						location.reload(true);
						clear_input()
       		}
			});
			$('#payenderror').show()
			dialog_payenderror.open();
		}
		var remark = htmlEncode($("#remark").val());

		$('#dialog_addr').html(txDest);
		$('#send_addr').html(txDest);
		$('#send_type').html(coin_en);
		$('#dialog_coin').html(coin_zh);
		$('#coin_type').html(coin_en);
		$('#dialog_coin_num').html(total_amount);
		$('#send_coin').html(total_amount);
		$('#dialog_cny_num').html(cny_num);
		$('#send_cny').html(cny_num);
		$('#dialog_free').html(tx_info.fee);
		$('#dialog_remark').html(remark);
		if($("#immediate").prop("checked")){
			$('#paytype_l').show()
			$('#paytype_r').show()
			$('#dialog_paytype').html(l('ImConfirm'));
			im = true;
		}else{
			$('#paytype_l').hide()
			$('#paytype_r').hide()

			im = false;
		}

		dialog_paycheck.close()
		dialog_checkinfo = new BootstrapDialog({
			type: 'type-default',
			title: l('ConfirmPay'),
				message: $('#checkinfo'),
				closable: true,
				closeByBackdrop: false,
				closeByKeyboard: false,
				autodestroy:false,
				onhide: function(dialogRef){
					clear_input()
       }
		});
		$('#checkinfo').show()
		dialog_checkinfo.open();
	})



	$("#pay").click(function (){
			 	dialog_gif = new BootstrapDialog({
				type: 'gif',
				title: '',
				message: $('#paygif'),
				closable: false,
				closeByBackdrop: false,
				closeByKeyboard: false,
				autodestroy:false
			});
			$('#paygif').show()
			dialog_gif.open();
			setTimeout(function(){ payRequest(tx_info.uuid, tx_info.ct,tx_info.tx,check_type,check_code,im) },3000)
			dialog_checkinfo.close()


	});

	function make_tx(){
		var passwd = $("#passwd").val();
		var sendTx = new Bitcoin.Transaction();
		var sum = 0;
		var secret = bitDecrypt(userData.payload, passwd);
		if(secret == 'error'){
			sendError(l('PayPwd_ErrWrong'),'sign_error');
			return ;
		}
		var sec = $.parseJSON(secret);
		var priv_lst = new Array()
		var vin_index = 0;
		tx_fee = 0 ;

		if(userData.free_fee != null && userData.free_fee[ct] != null)
		{
			tx_fee = 0
		}
		else
		{
			tx_fee = ct == "ltc" ? 100000 : 10000;
		}
		var tx_total_sum = 0;
		var send_amount = Math.round(total_amount * 1e8) + tx_fee;
		var uuid = null;

		var spent_addrs = new Array();
		var select_addr = $("#myaddr").val();
		if(select_addr)
		{
			$.each(userData.addrs, function(i, item){
				if(item["addr"] == select_addr)
				{
					spent_addrs.push(item);
				}
			})
		}
		else
		{
			spent_addrs = userData.addrs;
		}
		var change_addr = null;
		if(sec.keys.length >= spent_addrs.length)
		{
			for (var i = 0; i< sec.keys.length; i++)
			{
				if(send_amount <= tx_total_sum)
						break;
				var priv = sec.keys[i].priv;
				var pub = sec.keys[i].pub;
				for(var j = 0; j < spent_addrs.length; j++)
				{
					if(send_amount <= tx_total_sum)
						break;
					var redeemscript = spent_addrs[j].redeemscript;
					if (redeemscript.indexOf(pub) > -1)
					{
						var confirm_txs = spent_addrs[j].tx[ct]["cf"];
						for(var k = 0; k < confirm_txs.length; k++)
						{
							if(send_amount <= parseFloat(confirm_txs[k]["v"]))
							{
								var tx_hash = {'hash': Crypto.util.bytesToBase64(Crypto.util.hexToBytes(confirm_txs[k].t.match(/.{1,2}/g).reverse().join("")))};
								sendTx.addInput(tx_hash, confirm_txs[k].n);
								sendTx.ins[vin_index].script = new Bitcoin.Script(Crypto.util.hexToBytes(redeemscript.toLowerCase()));
								if(change_addr == null)
									change_addr = new Bitcoin.Address(spent_addrs[j].addr);
								vin_index++;
								priv_lst.push(priv);
								tx_total_sum += parseFloat(confirm_txs[k]["v"]);
								break;
							}
						}
					}
				}
			}
			if(vin_index == 0)
			{
				for (var i = 0; i< sec.keys.length; i++)
				{
					if(send_amount <= tx_total_sum)
						break;
					var priv = sec.keys[i].priv;
					var pub = sec.keys[i].pub;
					for(var j = 0; j < spent_addrs.length; j++)
					{
						if(send_amount <= tx_total_sum)
							break;
						var redeemscript = spent_addrs[j].redeemscript;
						if (redeemscript.indexOf(pub) > -1)
						{
							var confirm_txs = spent_addrs[j].tx[ct]["cf"];
							for(var k = confirm_txs.length -1; k >=0 ; k--)
							{
								if(send_amount > tx_total_sum)
								{
									var tx_hash = {'hash': Crypto.util.bytesToBase64(Crypto.util.hexToBytes(confirm_txs[k].t.match(/.{1,2}/g).reverse().join("")))};
									sendTx.addInput(tx_hash, confirm_txs[k].n);
									sendTx.ins[vin_index].script = new Bitcoin.Script(Crypto.util.hexToBytes(redeemscript.toLowerCase()));
									vin_index++;
									if(change_addr == null)
										change_addr = new Bitcoin.Address(spent_addrs[j].addr);
									priv_lst.push(priv);
									tx_total_sum += parseFloat(confirm_txs[k]["v"]);
								}
								else
								{
									break;
								}
							}
						}
					}
				}
			}
			if(send_amount > tx_total_sum)
			{
				for (var i = 0; i< sec.keys.length; i++)
				{
					if(send_amount <= tx_total_sum)
						break;
					var priv = sec.keys[i].priv;
					var pub = sec.keys[i].pub;
					for(var j = 0; j < spent_addrs.length; j++)
					{
						if(send_amount <= tx_total_sum)
							break;
						var redeemscript = spent_addrs[j].redeemscript;
						if (redeemscript.indexOf(pub) > -1)
						{
							var unconfirm_txs = spent_addrs[j].tx[ct]["u_cf"];
							for(var k = unconfirm_txs.length -1; k >=0 ; k--)
							{
								if(send_amount > tx_total_sum)
								{
									var tx_hash = {'hash': Crypto.util.bytesToBase64(Crypto.util.hexToBytes(unconfirm_txs[k].t.match(/.{1,2}/g).reverse().join("")))};
									sendTx.addInput(tx_hash, unconfirm_txs[k].n);
									sendTx.ins[vin_index].script = new Bitcoin.Script(Crypto.util.hexToBytes(redeemscript.toLowerCase()));
									vin_index++;
									if(change_addr == null)
										change_addr = new Bitcoin.Address(spent_addrs[j].addr);
									priv_lst.push(priv);
									tx_total_sum += parseFloat(unconfirm_txs[k]["v"]);
								}
								else
								{
									break;
								}
							}
						}
					}
				}
			}
			if(userData.free_fee != null && userData.free_fee[ct] != null)
			{
				var tx_fee_hash = {'hash': Crypto.util.bytesToBase64(Crypto.util.hexToBytes(userData.free_fee[ct].txid.match(/.{1,2}/g).reverse().join("")))};
				sendTx.addInput(tx_fee_hash, userData.free_fee[ct].n);
				uuid = userData.free_fee[ct].uuid;
			}
			var addr = $.trim($("#address").val());
			var res = parseBase58Check(addr);
			var addr = new Bitcoin.Address(addr);
			if(res['result']==1){
				var amount = $("#amount").val();
				if(!isNaN(amount) && amount*1>0){
					var amount = new BigInteger('' + Math.round((amount*1) * 1e8), 10);
					sendTx.addOutput(addr, amount);
				}
			}
			var change = tx_total_sum - send_amount;
			if (change > 600)
			{
				sendTx.addOutput(change_addr, new BigInteger('' + change, 10));
			}
			else if(change < 0)
			{
				return;
			}
			var txNew = new Bitcoin.Transaction(sendTx);
			if(sendTx.ins.length == priv_lst.length || sendTx.ins.length == priv_lst.length+1)
			{
				$.each(sendTx.ins, function(i, o){
					var priv = priv_lst[i];;
					if(priv != null)
					{
						var redeemscript = (o.script.chunks[o.script.chunks.length-1]==174) ? o.script : new Bitcoin.Script(o.script.chunks[o.script.chunks.length-1]);
						var secret = Bitcoin.Base58.decode(priv).slice(1, 33);
						var eckey = new Bitcoin.ECKey(secret);
						var sighash = txNew.hashTransactionForSignature(redeemscript, i, 1);
						var signature = eckey.sign(sighash);
						signature.push(parseInt(1, 10));

						var s = new Bitcoin.Script();
						s.writeOp(0);

						if(o.script.chunks[o.script.chunks.length-1]==174){
							s.writeBytes(signature);
						}
						else if (o.script.chunks[0]==0 && o.script.chunks[o.script.chunks.length-1][o.script.chunks[o.script.chunks.length-1].length-1]==174){
							var pubkeyList = scriptListPubkey(redeemscript);
							var sigsList = scriptListSigs(o.script);
							sigsList[countObject(sigsList)+1] = signature;
							for(x in pubkeyList){
								for(y in sigsList){
									if(Bitcoin.ECDSA.verify(sighash, sigsList[y], pubkeyList[x])){
										s.writeBytes(sigsList[y]);
									}
								}
							}
						}
						s.writeBytes(redeemscript.buffer);
						txNew.ins[i].script = s;
					}
				});
			}
			return {uuid:uuid,ct:ct,tx:Crypto.util.bytesToHex(txNew.serialize()), fee:tx_fee ==0 ? l('Free'): getbtcvalue(tx_fee)}
		}
	}


})
})(jQuery);
